<template>
    <div class="e-form">
        <BillTop title="租赁验收编辑" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="租赁验收明细" name="planDetail" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form ref="form" :model="formData.handoverLease" label-width="170px" :rules="rules">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="验收编号：">
                                            <span>{{ formData.handoverLease.billNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="验收日期：" prop="acceptanceDate">
                                            <el-date-picker
                                                v-model="formData.handoverLease.acceptanceDate"
                                                type="date"
                                                placeholder="选择日期"
                                                value-format="yyyy-MM-dd"
                                                :clearable="false"
                                            >
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="租赁类型：" prop="leaseType">
                                            <el-select v-model="formData.handoverLease.leaseType"  @change="selectLeaseType">
                                                <el-option :value="item.value" :label="item.label" v-for="item,index in leaseTypeList" :key="index" ></el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="出租单位：">
                                            <el-input v-model="formData.handoverLease.leaseUnit" readonly v-if="formData.handoverLease.leaseType == '2' ">
                                                <i slot="suffix" class="el-input__icon el-icon-document-copy" @click="selectLeaseUnit"></i>
                                            </el-input>
                                            <span v-else>{{ formData.handoverLease.leaseUnit }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="源单编号：" prop="originalNo">
                                            <el-col :span="19">
                                                <el-input v-model="formData.handoverLease.originalNo" readonly>
                                                    <i slot="suffix" class="el-input__icon el-icon-document-copy" @click="selectOriginalNo"></i>
                                                </el-input>
                                            </el-col>
                                            <el-col :span="5" v-if="formData.handoverLease.leaseType != 1">
                                                <el-link type="primary" :underline="false" @click="lookSource">查看源单</el-link>
                                            </el-col>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="验收地点：" prop="acceptanceSiteDetails">
                                            <SelectAddr v-model="formData.handoverLease.acceptanceSiteDetails"
                                                lazy
                                                showCountry
                                            ></SelectAddr>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="验收人：">
                                            <span>{{ formData.handoverLease.handoverPeople }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                        <span>{{ statusLable(formData.handoverLease.state) }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="机构：">
                                            <span>{{ formData.handoverLease.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item  label="验收情况：">
                                            <el-input type="textarea" v-model="formData.handoverLease.remarks" placeholder="请输入内容"></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="planDetailCon" class="con">
                        <div class="tabs-title" id="planDetail">租赁验收明细</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button  class="btn-greenYellow" @click="planListAdd">新增</el-button>
                                        <el-button  class="btn-delete" @click="deletePlanList" v-if="isBatch[0].flag">批量删除</el-button>
                                    </div>
                                    <div class="batchBox" @click="batchOperation('planDetail')">
                                        <img class="batchicon" src="@/assets/piliang.png">
                                        <span class="batchfont">{{isBatch[0].batch}}</span>
                                    </div>
                                </div>
                            </div>
                            <div class="errorMsg" v-if="errorMsg.length>0">
                                <span v-for="item,index in errorMsg" :key="index">
                                    {{item}}
                                </span>
                            </div>
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="planTable"
                                :data="handoverPurchaseDtlListCopy"
                                border
                                style="width: 100%"
                                @selection-change="planTableSelect"
                                v-sortTable="{ 'tableData': handoverPurchaseDtlListCopy, '_this': this, 'ref': 'planTable' }"
                            >
                                <el-table-column type="selection" width="55" align="center" v-if="isBatch[0].flag">
                                </el-table-column>
                                <el-table-column  fixed type="index" label="序号" width="80" align="center">
                                </el-table-column>
                                <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{ row,$index }">
                                        <div class="handle">
                                            <div style=" cursor: pointer;">
                                                <img src="@/assets/btn/delete.png"  @click="handleDelete(row,$index)">
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="equipmentNo"
                                    label="设备编号"
                                    min-width="180"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="equipmentName"
                                    label="设备名称"
                                    min-width="180"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="categoryName"
                                    label="设备类别"
                                    min-width="180"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="specificationModel"
                                    label="规格型号"
                                    min-width="180"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="计量单位"
                                    width="120"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="plateNo"
                                    label="车牌号"
                                    width="180"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.plateNo" clearable @input="curStateChange(row)"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    label="计时单位"
                                    width="150"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-select v-model="row.timeUnit" placeholder="请选择" @input="curStateChange(row)">
                                            <el-option v-for="item,index in timeUnitList" :key="index" :value="item.value" :label="item.label"></el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="approachNum"
                                    label="进场公里数/小时"
                                    width="150"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.approachNum" clearable
                                        @input="curStateChange(row)"
                                        v-enter-float="{
                                            set: row,
                                            key: 'approachNum'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="approachPrice"
                                    label="进场费（元）"
                                    width="200"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.approachPrice" clearable
                                        v-if="row.type != 0"
                                        @input="curStateChange(row)"
                                        v-enter-float="{
                                            set: row,
                                            key: 'approachPrice'
                                        }"></el-input>
                                        <span v-else>{{row.approachPrice}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="singlePrice"
                                    label="单机租金（元）"
                                    width="170"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.singlePrice" clearable
                                        v-if="formData.handoverLease.type != 0"
                                        @input="curStateChange(row)"
                                            v-enter-float="{
                                            set: row,
                                            key: 'singlePrice'
                                        }"></el-input>
                                        <span v-else>{{row.singlePrice}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="leaseTerm"
                                    label="租赁时间"
                                    width="150"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.leaseTerm" clearable
                                         @input="curStateChange(row)"
                                            v-enter-float="{
                                            set: row,
                                            key: 'leaseTerm'
                                        }" v-if="formData.handoverLease.type != 0"></el-input>
                                        <span v-else>{{row.leaseTerm}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="isMaintenance"
                                    label="是否保养"
                                    width="150"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span v-if="formData.handoverLease.leaseType == 1">{{row.isMaintenance ? isMaintenance[row.isMaintenance].label :''}}</span>
                                        <el-select v-model="row.isMaintenance" placeholder="请选择" @input="curStateChange(row)" v-else>
                                            <el-option v-for="item,index in isMaintenance" :key="index" :value="item.value" :label="item.label"></el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="manufacturer"
                                    label="出产厂商"
                                    width="200"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.manufacturer" clearable @input="curStateChange(row)"  v-if="!row.isManufacturer"></el-input>
                                        <span v-else>{{row.manufacturer}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="factoryNo"
                                    label="出厂编号"
                                    width="200"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.factoryNo" clearable
                                        v-if="!row.isFactoryNo"
                                        @input="curStateChange(row)"></el-input>
                                        <span v-else>{{row.factoryNo}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="factoryTime"
                                    label="出厂日期"
                                    width="150"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-date-picker type="date" placeholder="选择日期" v-model="row.factoryTime" style="width: 100%;" value-format="yyyy-MM-dd" @input="curStateChange(row)"></el-date-picker>
                                    </template>
                                </el-table-column>
                                 <el-table-column
                                    prop="approachTime"
                                    label="进场时间"
                                    width="150"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-date-picker type="date" placeholder="选择日期" v-model="row.approachTime" style="width: 100%;" value-format="yyyy-MM-dd" @input="curStateChange(row)"></el-date-picker>
                                    </template>
                                </el-table-column>
                                 <el-table-column
                                    prop="expectedLeaveTime"
                                    label="预计退场时间"
                                    width="160"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-date-picker type="date" placeholder="选择日期" v-model="row.expectedLeaveTime" style="width: 100%;" value-format="yyyy-MM-dd" @input="curStateChange(row)"></el-date-picker>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="equiomentSituation"
                                    label="设备状况"
                                    width="150"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-select v-model="row.equiomentSituation" @input="curStateChange(row)">
                                            <el-option
                                                v-for="(
                                                    item,index
                                                ) in equipCondition"
                                                :key="index"
                                                :label="item.label"
                                                :value="item.value"
                                            >
                                            </el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                                 <el-table-column
                                    prop="theoryNum"
                                    label="理论工作总台班数"
                                    width="160"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.theoryNum" clearable
                                         @input="curStateChange(row)"
                                            v-enter-float="{
                                            set: row,
                                            key: 'theoryNum'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                                 <el-table-column
                                    prop="operatorPrice"
                                    label="操作手工资（元）"
                                    width="160"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.operatorPrice" clearable
                                         @input="curStateChange(row)"
                                            v-enter-float="{
                                            set: row,
                                            key: 'operatorPrice'
                                        }" v-if="row.type != 0 && formData.handoverLease.leaseType == 2"></el-input>
                                        <span v-else>{{ row.operatorPrice = row.allOperatorPrice && row.leaseTerm? parseFloat(new Number(row.allOperatorPrice / row.leaseTerm).toFixed(2)) : 0 }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    label="技术参数"
                                    width="120"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-button size="mini" class="btn-blue" @click="paramsAdd(row)"
                                            >编辑</el-button>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    label="上传附件"
                                    width="120"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-button size="mini" class="btn-blue" @click="uploadAttchInfo(row)">
                                            上传附件
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <span style="margin: 0 0 0 10px; color: #999; line-height: 35px"
                                    >温馨提示：请在租赁验收明细中上传每个设备的验收资料，“附件信息”显示所有设备上传的验收附件。</span>
                                </div>
                            </div>
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                :data="attachTableData"
                                border
                                style="width: 100%"
                                ref="table"
                            >
                                <el-table-column show-overflow-tooltip prop="objectPath" min-width="200" label="缩略图">
                                    <template slot-scope="{ row }" :size="60">
                                        <el-image
                                            v-if="
                                                'jpg,jpeg,png'.includes(row.objectName.split('.').pop().toLowerCase())
                                            "
                                            style="width: 100px; height: 100px"
                                            :src="row.objectPath"
                                            :preview-src-list="[row.objectPath]"
                                        >
                                        </el-image>
                                        <el-image v-else style="width: 100px; height: 100px" :src="pdfImg"></el-image>
                                    </template>
                                </el-table-column>
                                <el-table-column show-overflow-tooltip prop="objectName" min-width="200" label="文件名称">
                                </el-table-column>
                                <el-table-column show-overflow-tooltip prop="objectSize" label="文件大小" width="150">
                                    <template slot-scope="{ row }">
                                        {{ bytesToSize(row.objectSize) }}
                                    </template>
                                </el-table-column>
                                <el-table-column show-overflow-tooltip prop="gmtCreate" min-width="200" label="上传时间">
                                </el-table-column>
                                <el-table-column show-overflow-tooltip prop="userName" min-width="150" label="上传人">
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                billType="4013"
                                :tableData.sync="auditHistoryTable"
                                @getAuditHistory="getAuditHistory"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <ComExaButtons :auditState="auditState" :state="formData.handoverLease.state" @exas="exas" :founderId="formData.handoverLease.founderId" />
            <el-button size="small" @click="handleClose" v-debounce>取消</el-button>
        </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import $ from 'jquery'
import request from '@/api/equip/purchaseAcceptance.js'
import '@/utils/jquery.scrollTo.min'
import SelectAddr from '@/components/common/addrComp'
import ComAuditHistoryIndex from '@/pages/equipment/components/auditHistory/auditHistoryIndex'
import { getCurrentUnitInfo, history } from '@/api/equip/handoverAudit.js'
import { exas, saveAll, submitCommit } from '@/pages/equipment/components/auditHistory/equipCom.js'
import { openAppClient, hideLoading, showLoading } from '@/utils/common'
import { ip } from '@/utils/request'
import { selectLeaseMoveEquip, selectLeaseplanContract, selectLeaseAcceptDtl, removeRepetition } from '@/api/equip/popupCallback.js'
import ossRequest from '@/api/oss/oss.js'
import { bytesToSize, selectDataClient } from '@/utils/common'
import pdfImg from '@/assets/pdf_icon.png'

export default {
    data () {
        return {
            isBatch: [
                {
                    flag: true,
                    batch: '进入批量管理'
                },
            ],
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            formData: {
                //基础信息
                'handoverLease': {
                    'acceptanceDate': '',
                    'acceptanceSite': '',
                    'acceptanceSiteDetails': '',
                    'acceptanceSiteList': [],
                    'acceptanceSiteNumber': '',
                    'acceptanceSiteNumberList': [],
                    'acceptanceType': '',
                    'auditDate': '',
                    'auditor': '',
                    'auditorId': '',
                    'billDate': '',
                    'billId': '',
                    'billNo': '',
                    'contractId': '',
                    'contractName': '',
                    'contractNo': '',
                    'founderId': '',
                    'founderName': '',
                    'gmtCreate': '',
                    'gmtModified': '',
                    'handoverPeople': '',
                    'handoverPeopleId': '',
                    'leasePlanId': '',
                    'leasePlanNo': '',
                    'leaseType': '',
                    'leaseUnit': '',
                    'leaseUnitId': '',
                    'modifier': '',
                    'modifierId': '',
                    'nullifyCreated': '',
                    'nullifyCreator': '',
                    'nullifyCreatorId': '',
                    'nullifyDescription': '',
                    'nullifyReason': '',
                    'orgId': '',
                    'orgName': '',
                    'originalNo': '',
                    'recorder': '',
                    'recorderId': '',
                    'remarks': '',
                    'shortCode': '',
                    'state': 0,
                    'supplierId': '',
                    'supplierName': '',
                    'workId': '',
                    'type': ''
                },
            },
            rules: {
                acceptanceDate: [
                    { required: true, message: '请选择验收日期', trigger: 'change' },
                ],
                leaseType: [
                    { required: true, message: '请选择租赁类型', trigger: 'change'  },
                ],
                originalNo: [
                    { required: true, message: '请选择源单编号', trigger: 'change' },
                ],
                acceptanceSiteDetails: [
                    { required: true, message: '请选择验收地点', trigger: 'change' },
                ],
            },
            billid: this.$route.query.billid,
            handoverPurchaseDtlList: [],
            handoverPurchaseDtlListCopy: [],
            auditHistoryTable: [],
            planSelect: [], //采购验收明细选择项
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //计划明细错误显示
            isErrorMsg: true, //是否提醒错误信息
            currentRow: {},
            auditState: {}, //流程按钮显示状态
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 4013,
                'freeNextUnitIndex': null,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': '',
                'orgId': '',
                'orgName': '',
                'userId': '',
                'workId': ''
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 4013,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
            isMaintenance: [
                { value: '0', label: '否' },
                { value: '1', label: '是' },
            ], //是否保养
            uploadUrl: ip + '/oss/uploader',
            accept: '.jpg,jpeg,.png,.pdf',
            isReadonly: false,
            attachTableData: [], //附件信息表格
            pdfImg,
            oldLeaseType: '',
            res: ''
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            leaseTypeList: state=>state.equip.equipData.leaseTypeList, //租赁类型
            timeUnitList: state => state.equip.equipData.timeUnitList, //计时单位
            equipCondition: state=>state.equip.equipData.equipCondition, //设备状况
            unitMeasure: state => state.equip.equipData.unitMeasure //计量单位
        }),
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>x.value === param)
                return obj ? obj.label : ''
            }
        },
        //当前单据状态
        state () {
            return this.formData.handoverLease.state
        },
        attachId () {
            return this.$route.query.billid
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        orgCode () {
            return this.$store.state.userInfo.orgInfo.shortCode
        },
        bucketName () {
            return 'facilityconnect'
        },
    },
    components: {
        ComAuditHistoryIndex,
        SelectAddr
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
        //获取租赁类型切换前的值
        'formData.handoverLease.leaseType': function (newVal, oldVal) {
            this.oldLeaseType = oldVal
        },
        //监听附件信息表格改变
        // '$store.state.attachTable': {
        //     handler (newVal, oldVal) {
        //         this.attachTableData = newVal ? newVal : oldVal
        //     },
        //     deep: true
        // },
    },
    created () {
        this.getDicValue()
    },
    mounted () {
        this.init()
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'planDetail', 'attach', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    console.log('item', item)
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    methods: {
        //获取当前使用的字典
        getDicValue () {
            this.$store.dispatch('equip/setTimeUnitList')
            this.$store.dispatch('equip/setUnitMeasur')
        },
        ...mapMutations(['setAuditParams', 'setAttachTable', 'setSelectedInfo']),
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //是否进入批量操作
        batchOperation (name) {
            switch(name) {
            case 'planDetail':
                this.isBatch[0].flag = !this.isBatch[0].flag
                if(this.isBatch[0].flag) {
                    this.isBatch[0].batch = '退出批量管理'
                    this.$refs.planTable.clearSelection()
                }else{
                    this.isBatch[0].batch = '进入批量管理'
                }
                break
            }
        },
        //初始化数据
        init () {
            showLoading()
            Promise.all([
                this.getInfo(),
                this.getObjectByRelationId(this.billid),
                this.getPlanList(),
                this.getAuditHistory(),
                this.getCurrentUnitInfo(),
            ]).finally(() => {
                hideLoading()
            })
        },
        getInfo () {
            const params = {
                id: this.billid,
            }
            request.leaseAcceptanceBaseInfo(params).then(res=>{
                this.formData.handoverLease = res.handoverLease
            })
        },
        getPlanList () {
            const params = {
                planId: this.billid,
                userId: this.userId
            }
            request.leaseAcceptancePlanInfo(params).then(res=>{
                this.handoverPurchaseDtlListCopy = []
                res.handoverLeaseDtlList.map(item=>{
                    item.isNewAdd = false //判断是否是新增的数据
                    this.handoverPurchaseDtlListCopy.push(item)
                })
                this.handoverPurchaseDtlList = res.handoverLeaseDtlList
                if(this.handoverPurchaseDtlListCopy.length === 0) {
                    this.attachDel(false)
                    this.setAttachTable([])
                }
            })
        },
        //获取状态按钮
        getCurrentUnitInfo () {
            getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //刷新历史审核列表
        getAuditHistory () {
            history(this.auditParams).then(res=>{
                this.auditHistoryTable = res
            })
        },
        //========基本信息===========
        selectOriginalNo () {
            if(this.formData.handoverLease.leaseType == '') {
                this.clientPop('err', '请选择租赁类型！')
                return
            }
            this.clientPop(
                'info',
                '切换租赁类型明细及源单编号将被清空，是否继续?',
                ()=>{
                    this.handoverPurchaseDtlListCopy = []
                    this.handoverPurchaseDtlList.forEach(item=>{
                        item.changeType = -1
                    })
                    if(this.formData.handoverLease.leaseType == 1) {
                        let ids = this.formData.handoverLease.contractId ? [this.formData.handoverLease.contractId] : []
                        selectLeaseMoveEquip(ids).then(res=>{ //选择设备调动
                            res.forEach(item=>{
                                this.formData.handoverLease.originalNo = item.billNo
                                this.formData.handoverLease.leaseUnit = item.transferOrg
                                this.formData.handoverLease.leaseUnitId = item.transferOrgId
                                this.formData.handoverLease.contractId = item.billId
                                this.formData.handoverLease.type = item.type
                            })
                        })
                    }else{
                        let ids = this.formData.handoverLease.contractId ? [this.formData.handoverLease.contractId] : []
                        selectLeaseplanContract(ids, this.formData.handoverLease.leaseType).then(res=>{ //选择租赁计划/合同
                            res.forEach(item=>{
                                this.formData.handoverLease.originalNo = item.billNo
                                if(this.formData.handoverLease.leaseType != 2) {
                                    this.formData.handoverLease.leaseUnit = item.transferOrg
                                    this.formData.handoverLease.leaseUnitId = item.transferOrgId
                                }
                                this.formData.handoverLease.contractId = item.billId
                                this.formData.handoverLease.type = item.type
                            })
                        })
                    }
                },
                null,
                ()=>{}
            )
        },
        //切换租赁类型
        selectLeaseType () {
            this.clientPop(
                'info',
                '切换租赁类型明细及源单编号将被清空，是否继续?',
                ()=>{
                    this.formData.handoverLease.originalNo = ''
                    this.formData.handoverLease.leaseUnit = ''
                    this.formData.handoverLease.leaseUnitId = ''
                    this.formData.handoverLease.contractId = ''
                    this.formData.handoverLease.type = ''
                    this.handoverPurchaseDtlListCopy = []
                    this.handoverPurchaseDtlList.forEach(item=>{
                        item.changeType = -1
                    })
                    this.attachDel(false)
                    this.selectOriginalNo()
                },
                null,
                ()=>{
                    this.formData.handoverLease.leaseType = this.oldLeaseType
                }
            )
        },
        //为临租选择出租单位
        selectLeaseUnit () {
            const obj = {
                'businessUnitTypes': [],
                'keyword': '',
                'limit': 10,
                'orgId': '',
                'outerTypes': [],
                'page': 1,
                'states': [],
                'type': [0, 1, 2]
            }
            return selectDataClient({
                SelectServiceToken: 'GeneralSelectOuter', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [this.formData.handoverLease.leaseUnitId], // 已选中id
                InitParamsStr: JSON.stringify(obj),    // 接口参数(name为模拟参数)
                Title: '选择出租单位' // 标题
            }).then(res=>{
                this.formData.handoverLease.leaseUnit = res[0].outerName
                this.formData.handoverLease.leaseUnitId = res[0].id
            })
        },
        //查看源单
        lookSource () {
            if(!this.formData.handoverLease.contractId) {
                this.clientPop('err', '请选择源单编号' )
                return
            }
            if(this.formData.handoverLease.type == 1) {
                openAppClient(`/leasePlanShow?billid=${this.formData.handoverLease.contractId}&isview=true`, '租赁计划')
            }else{
                openAppClient(`/ctEquipmentLeaseApplyShow?billid=${this.formData.handoverLease.contractId}&isview=true`, '设备租赁合同')
            }
        },
        //========计划明细============
        //判断当前状态是否已修改
        curStateChange (row) {
            this.currentRow = row
            if (row.leaseDtlId) {
                if(row.isNewAdd) {
                    this.currentRow.changeType = 1
                }else{
                    this.currentRow.changeType = 2
                }
            }
            if(row.type == 0 && this.formData.handoverLease.leaseType != 2) {
                row.operatorPrice = row.allOperatorPrice ? parseFloat(new Number(row.allOperatorPrice / row.leaseTerm).toFixed(2)) : 0
            }
        },
        //添加租赁验收
        planListAdd () {
            let json = {
                'billId': this.formData.handoverLease.contractId, //单据id 必传
                'leaseType': +this.formData.handoverLease.leaseType, //(0:外租|1:内租|2:临租)
                'type': this.formData.handoverLease.type //(0 合同 1 计划)
            }
            let ids = []
            ids = this.handoverPurchaseDtlListCopy.map(x=>x.contractDtlId)
            let idsObj = []
            idsObj.push(JSON.stringify({ 'contractId': this.formData.handoverLease.contractId, 'ids': ids }))
            selectLeaseAcceptDtl(json, idsObj).then(res=>{
                this.res = res
                res.forEach(item=>{
                    item.equiomentSituation = '0'
                    item.billId = this.billid
                    item.changeType = 1
                    //如果是内租  是否保养时根据调动单保养承担方来获取 调入机构为是 调出机构为否
                    if(this.formData.handoverLease.leaseType != 1) {
                        item.isMaintenance = null
                        const arr = this.handoverPurchaseDtlList.filter(x=>x.contractDtlId === item.contractDtlId && x.changeType !== -1)
                        let len = item.unAcceptanceQuantity - arr.length
                        for(let i = 0 ;i < len ;i++) {
                            let obj = {
                                'acceptanceQuantity': 0,
                                'accountId': '',
                                'allOperatorPrice': 0,
                                'approachNum': 0,
                                'approachPrice': 0,
                                'approachTime': '',
                                'billId': '',
                                'billNo': '',
                                'categoryId': '',
                                'categoryName': '',
                                'changeType': 0,
                                'contractDtlId': '',
                                'equiomentSituation': '',
                                'equipmentId': '',
                                'equipmentName': '',
                                'equipmentNo': '',
                                'equipmentState': 0,
                                'expectedLeaveTime': '',
                                'factoryNo': '',
                                'factoryTime': '',
                                'gmtCreate': '',
                                'gmtModified': '',
                                'isFactoryNo': true,
                                'isMaintenance': '',
                                'isSettle': true,
                                'leaseAmount': 0,
                                'leaseDtlId': '',
                                'leaseTerm': 0,
                                'leaseTime': 0,
                                'maintainUnit': 0,
                                'manufacturer': '',
                                'oneLevelCategoryId': '',
                                'oneLevelCategoryName': '',
                                'operatorPrice': 0,
                                'origEquiomentNo': '',
                                'plateNo': '',
                                'quantity': 0,
                                'singlePrice': 0,
                                'specificationModel': '',
                                'state': 0,
                                'theoryNum': 0,
                                'timeUnit': '',
                                'type': 0,
                                'unAcceptanceQuantity': 0,
                                'unit': '',
                                ...item
                            }
                            this.$Ajax
                                .httpGet({
                                    url: '/uid/builder?num=1',
                                    headers: {
                                        'Content-Type': 'application/x-www-form-urlencoded'
                                    }
                                }).then(res=>{
                                    obj.leaseDtlId = res[0]
                                    obj.isNewAdd = true //判断是否是新增的数据
                                    if(this.formData.handoverLease.leaseType == 1 && obj.manufacturer != '') {  //如果租赁类型是内租并且出产厂商为空 出产厂商不可以填写 反之
                                        obj.isManufacturer = true //出产厂商 不可以修改
                                    }else{
                                        obj.isManufacturer = false //出产厂商 可以修改
                                    }
                                    if(this.formData.handoverLease.leaseType == 1 && obj.factoryNo != '') { //如果租赁类型是内租并且出厂编号为空 出厂编号不可以填写 反之
                                        obj.isFactoryNo = true //出厂编号 不可以修改
                                    }else{
                                        obj.isFactoryNo = false //出厂编号 不可以修改
                                    }
                                })
                            this.handoverPurchaseDtlListCopy.push(obj)
                            this.handoverPurchaseDtlList.push(obj)
                        }
                    }else{
                        item.isMaintenance = item.maintainUnit + ''
                        //前端生成id
                        this.$Ajax
                            .httpGet({
                                url: '/uid/builder?num=1',
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded'
                                }
                            }).then(res=>{
                                item.leaseDtlId = res[0]
                                item.isNewAdd = true //判断是否是新增的数据
                                if(this.formData.handoverLease.leaseType == 1 && item.manufacturer != '') {  //如果租赁类型是内租并且出产厂商为空 出产厂商不可以填写 反之
                                    item.isManufacturer = true //出产厂商 不可以修改
                                }else{
                                    item.isManufacturer = false //出产厂商 可以修改
                                }
                                if(this.formData.handoverLease.leaseType == 1 && item.factoryNo != '') { //如果租赁类型是内租并且出厂编号为空 出厂编号不可以填写 反之
                                    item.isFactoryNo = true //出厂编号 不可以修改
                                }else{
                                    item.isFactoryNo = false //出厂编号 不可以修改
                                }
                            })
                        this.handoverPurchaseDtlListCopy.push(item)
                        this.handoverPurchaseDtlList.push(item)
                        this.handoverPurchaseDtlListCopy = removeRepetition({
                            'arr': this.handoverPurchaseDtlListCopy,
                            'id': 'contractDtlId'
                        })
                        this.handoverPurchaseDtlList = removeRepetition({
                            'arr': this.handoverPurchaseDtlList,
                            'id': 'contractDtlId'
                        })
                    }
                })

            })
        },
        //技术参数非空验证
        verifySkillTable () {
            return new Promise((resolve, reject)=>{
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                this.errorSkillMsg = []
                let flagMaterial =  auditParams.table.some(x=>{
                    if(x.changeType !== -1) {
                        return x.parameterName === null || x.parameterName === '' || x.parameterValue === null || x.parameterValue === ''
                    }
                })
                if(flagMaterial) {
                    let str = '技术参数未填写完整，请检查！'
                    this.errorSkillMsg.push(str)
                    this.setAuditParams({ 'errorMsg': this.errorSkillMsg })
                }
                this.errorSkillMsg.length > 0 ? reject() : resolve()
            })
        },
        //添加参数信息
        paramsAdd (row) {
            this.setAuditParams({ id: row.leaseDtlId })
            // 客户端弹窗弹出本地页面
            openAppClient('/leaseSkillParameterEdit', '参数编辑', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                request.updateLeaseTechnical(auditParams.table).then(()=>{
                    this.clientPop('suc', '保存成功')
                })
            })
        },
        //上传附件信息
        uploadAttchInfo (row) {
            this.setAuditParams({ id: row.leaseDtlId, billid: this.billid, isView: false })
            // 客户端弹窗弹出本地页面
            openAppClient('/leaseAcceptanceAttachEdit', '附件信息', ()=>{
                this.getObjectByRelationId(this.billid)
            }, null, ()=>{
                this.getObjectByRelationId(this.billid)
            })
        },
        //获取上传的对象
        getObjectByRelationId (relationId) {
            return ossRequest.getObjectByRelationId({ relationId: relationId }).then(res => {
                this.attachTableData = res
            })
        },
        //删除附件信息
        attachDel (id, flag) {
            let recordIds = []
            if(flag) {  //删除对应行的附件
                this.attachTableData.map(value => {
                    if(id === value.relationIdTag) {
                        recordIds.push(value.recordId)
                    }
                })
            }else{ //删除单据的附件
                recordIds = this.attachTableData.map(value => value.recordId)
            }
            const promiseArr = []
            showLoading()
            if(recordIds.length > 0) {
                recordIds.forEach(value => {
                    promiseArr.push(ossRequest.deleterRecordId({ recordId: value }))
                })
                Promise.all(promiseArr)
                    .then(() => {
                        this.getObjectByRelationId(this.billid)
                    })
                    .catch(() => {
                        this.clientPop('err', '部分数据删除失败', this.getObjectByRelationId(this.billid))
                    })
                    .finally(() => {
                        hideLoading()
                    })
            }else{
                hideLoading()
            }
        },
        //文件大小
        bytesToSize (byte) {
            return bytesToSize(byte)
        },
        //单个删除
        handleDelete (row, $index) {
            this.clientPop('info', this.oneDeleteErr, ()=>{
                let length = this.errorMsg.length
                if(row.leaseDtlId) {
                    this.handoverPurchaseDtlListCopy.splice($index, 1)
                    if(!row.isNewAdd) {
                        this.$set(this.handoverPurchaseDtlList[$index], 'changeType', -1)
                    }else{
                        this.handoverPurchaseDtlList.splice($index, 1)
                    }
                    if (length > 0 ) {
                        this.verifyTable()
                    }
                }
                this.attachDel(row.leaseDtlId, true)
            })
        },
        //获取采购验收明细表格的选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //删除采购验收明细列表
        deletePlanList () {
            const length = this.planSelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    this.delete
                )
            }
        },
        delete () {
            this.planSelect.filter(row=>{
                this.handoverPurchaseDtlListCopy.map((x, index)=>{
                    if(row == x ) {
                        this.handoverPurchaseDtlListCopy.splice(index, 1)
                    }
                })
                if(row.leaseDtlId) {
                    if(!row.isNewAdd) {
                        const index = this.handoverPurchaseDtlList.findIndex(item=>{
                            return item.leaseDtlId == row.leaseDtlId
                        })
                        this.$set(this.handoverPurchaseDtlList[index], 'changeType', -1)
                    }else{
                        this.handoverPurchaseDtlList.map((x, index)=>{
                            if(row == x ) {
                                this.handoverPurchaseDtlList.splice(index, 1)
                            }
                        })
                    }
                    if (length > 0 ) {
                        this.verifyTable()
                    }
                    this.$refs.planTable.clearSelection()
                }
                this.attachDel(row.leaseDtlId, true)
            })
        },
        //计划明细非空验证
        verifyTable () {
            return  new Promise((resolve, reject)=>{
                this.errorMsg = []
                this.handoverPurchaseDtlListCopy.forEach((item, index)=>{
                    if(item.changeType !== -1) {
                        // if(item.plateNo == null || item.plateNo == '') {
                        //     let str = `请填写第 ${index + 1} 行的（车牌号）`
                        //     this.errorMsg.push(str)
                        // }
                        if(item.timeUnit == null || item.timeUnit == '') {
                            let str = `请填写第 ${index + 1} 行的（计时单位）`
                            this.errorMsg.push(str)
                        }
                        // if(item.approachNum == null || item.approachNum == '') {
                        //     let str = `请填写第 ${index + 1} 行的（进场公里数/小时）`
                        //     this.errorMsg.push(str)
                        // }
                        if(item.singlePrice == null || item.singlePrice == '') {
                            let str = `请选择第 ${index + 1} 行的（单机租金（元））`
                            this.errorMsg.push(str)
                        }
                        if(item.leaseTerm == null || item.leaseTerm == '') {
                            let str = `请选择第 ${index + 1} 行的（租赁时间）`
                            this.errorMsg.push(str)
                        }
                        if(item.isMaintenance == null || item.isMaintenance == '') {
                            if(this.formData.handoverLease.leaseType != 1) {
                                let str = `请选择第 ${index + 1} 行的（是否保养）`
                                this.errorMsg.push(str)
                            }
                        }
                        if(item.manufacturer == null || item.manufacturer == '') {
                            let str = `请选择第 ${index + 1} 行的（出产厂商）`
                            this.errorMsg.push(str)
                        }
                        if(item.factoryNo == null || item.factoryNo == '') {
                            let str = `请选择第 ${index + 1} 行的（出厂编号）`
                            this.errorMsg.push(str)
                        }
                        if(item.factoryTime == null || item.factoryTime == '') {
                            let str = `请选择第 ${index + 1} 行的（出厂日期）`
                            this.errorMsg.push(str)
                        }
                        if(item.equiomentSituation == null || item.equiomentSituation == '') {
                            let str = `请选择第 ${index + 1} 行的（设备状况）`
                            this.errorMsg.push(str)
                        }
                        // if(item.theoryNum == null || item.theoryNum == '') {
                        //     let str = `请选择第 ${index + 1} 行的（理论工作总台班数）`
                        //     this.errorMsg.push(str)
                        // }
                        if(item.approachTime == '' || item.approachTime == null) {
                            let str = `请选择第 ${index + 1} 行的（预计进场时间）`
                            this.errorMsg.push(str)
                        }else{
                            if(item.exitDate !== '') {
                                const enterDate = new Date(item.approachTime).getTime() //预计进场时间
                                const exitDate = new Date(item.expectedLeaveTime).getTime() //预计退场时间
                                if(enterDate > exitDate) {
                                    let str = `第 ${index + 1} 行的（退场时间不能小于预计进场时间）`
                                    this.errorMsg.push(str)
                                }
                            }

                        }
                    }
                })
                if(this.errorMsg.length > 0) {
                    reject()
                }else{
                    resolve()
                }

            })

        },
        //取消
        handleClose () {
            this.$router.replace('/leaseAcceptanceList')
        },
        //更新基础信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                this.$refs.form.validate(valid => {
                    if(valid) {
                        request.leaseAcceptanceUpdate(this.formData).then(()=>{
                            resolve()
                        }).catch(err=>{
                            reject(err)
                            this.setError('baseInfo')
                            this.scorllError()
                        })
                    }else{
                        reject()
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        //更新计划明细
        updateDetailInfo () {
            return new Promise((resolve, reject)=>{
                this.verifyTable().then(()=>{
                    request.updateLeaseAcceptanceDtl(this.handoverPurchaseDtlList).then(()=>{
                        resolve()
                    }).catch(err=>{
                        reject(err)
                        this.setError('planDetail')
                        this.scorllError()
                    })
                }).catch(err=>{
                    this.setError('planDetail')
                    reject(err)
                    this.scorllError()
                })

            })
        },
        //保存全部数据
        saveAll () {
            this.errorList = []
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateDetailInfo()
                ]
            }
            saveAll(this, requestFn)
        },
        //保存并提交
        submitCommit () {
            if(this.handoverPurchaseDtlListCopy.length === 0) {
                let str = '计划明细不能空！'
                this.errorMsg.push(str)
                this.setError('planDetail')
                this.scorllError()
                return
            }
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateDetailInfo()
                ]
            }
            submitCommit(this, requestFn, 1)
        },
        // 审核相关操作
        async exas (arg) {
            const requestFn = ()=>{
                return []
            }
            exas(arg, this, requestFn, 1)
        },
        //删除单据
        deleteBills () {
            this.clientPop('info', this.oneDeleteErr, ()=>{
                request.leaseAcceptanceDelete({ idList: this.billid }).then(()=>{
                    this.clientPop('suc', '删除成功', this.handleClose)
                })
            })
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;
}

</style>
